<template>
  <div class="register">
    <!-- 标题 -->
    <div class="title">
      <h2>注册新用户</h2>
    </div>

    <!-- 主体 -->
    <div class="main">
      <!-- 左半部分 -->
      <div class="form-left">
        <el-col :span="24" :md="12">
          <el-form :model="registerForm" ref="registerForm" >
            <el-form-item label="用户名" prop="username">
              <el-input
                  v-model="registerForm.username"
                  placeholder="用户名"
                  class="form-input"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                  v-model="registerForm.password"
                  type="password"
                  placeholder="密码"
                  class="form-input"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input
                  v-model="registerForm.email"
                  placeholder="邮箱"
                  class="form-input"></el-input>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                  v-model="registerForm.birthday"
                  type="date"
                  placeholder="选择日期"
                  class="form-input"
                  format="yyyy年MM月dd日"
                  value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-form>
        </el-col>
      </div>

      <div class="divider">
      </div>

      <!-- 右半部分 -->
      <div class="upload-right">
        <el-col :span="24" :md="12">
          <div class="upload-header">请上传头像</div>
          <el-upload
              class="avatar-upload"
              action="#"
              :http-request="handleAvatar"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload">
            <img v-if="avatarUrl" :src="avatarUrl" class="avatar" alt="Avatar">
            <i v-else class="el-icon-plus avatar-upload-icon"></i>
          </el-upload>
          <el-button
              type="primary"
              class="submit-btn"
              @click="submitForm()">
            完成
          </el-button>
        </el-col>
      </div>
    </div>

    <!-- 底部 -->
    <div class="footer">
      <router-link to="/forget-password">忘记密码？</router-link>
      <router-link to="/">返回登录</router-link>
    </div>
  </div>
</template>

<script>
import user from '@/api/user';

export default {
  name: 'Register',
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
        email: '',
        birthday: '',
        avatar: ''
      },
      avatarFile: null, // 新增 avatarFile 字段存储上传的文件
      avatarUrl: '',
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度应在 3 到 20 个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度应在 6 到 20 个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        birthday: [
          { required: true, message: '请选择生日', trigger: 'change' }
        ],
        avatar: [
          { required: true, message: '请上传头像', trigger: 'change' }
        ]
      },
    };
  },
  methods: {
    //...mapActions(['setUser']),
    handleAvatar(param) {
      const file = param.file;
      this.avatarUrl = URL.createObjectURL(file); // 预览上传的头像
      this.avatarFile = file; // 存储上传的文件

      console.log('Uploading avatar:', file); // 控制台输出上传的文件信息

      user.avatarUpload(file)
          .then(response => {
            if (response.data) {
              this.registerForm.avatar = response.data; // 将返回的 UUID
              this.$message.success('头像上传成功！');
            } else {
              this.$message.error('上传失败');
            }
          })
          .catch(error => {
            this.$message.error('上传失败: ' + error.message);
          });
    },
    beforeAvatarUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGorPNG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPGorPNG && isLt2M;
    },
    submitForm() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          const userInfo = {
            username: this.registerForm.username,
            password: this.registerForm.password,
            email: this.registerForm.email,
            birthday: this.registerForm.birthday,
            avatar: this.registerForm.avatar
          };

          console.log('Sending user info:', userInfo); // 输出发送的数据
          user.register(userInfo, this.avatarFile)
              .then(response => {
                if (response.data) {
                  this.$message.success('注册成功');
                  this.$router.push('/');
                } else {
                  this.$message.error('注册失败');
                }
              }).catch(error => {
            this.$message.error('注册失败: ' + error.message);
          });
        } else {
          console.log('错误提交!!');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="stylus">
.register
  width 95%
  max-width 800px
  border-radius 8px
  overflow hidden
  z-index 1
  background #f0f0f0
  padding 2rem
  margin 2rem 2rem

  .title
    text-align center
    h2
      color #333
      font-size 1.5rem
      margin 0

  .main
    position relative
    margin 0 2rem 1rem
    display flex
    gap 2rem
    .el-col-md-12
      width 100%
      display block

    .form-left
      flex 1
      padding-right 2rem
      .form-input
        width 100%
        height: 40px;

    .divider
      content ""
      position absolute
      left 50%
      top 10%
      bottom 10%
      width 1px
      background #0b0b0b

    .upload-right
      flex 1
      padding-left 2rem
      text-align center
      .upload-header
        font-size 14px
        color #000000
        margin-bottom 5px
      .avatar-upload
        border 1px dashed #000000
        border-radius 6px
        cursor pointer
        width 300px
        margin 0 auto 3rem
        .avatar
          width 100%
          height 100%
          object-fit cover
        .avatar-upload-icon
          font-size 28px
          color #8c939d
          line-height 150px

  .footer
    display: flex
    justify-content: space-around
    padding: 1rem
    background: #505050
    margin: 0px -40px -40px
    height 30px
    border-radius: 0 0 8px 8px
    a
      color: white;
      text-decoration: none;
      font-size: 14px;
      &:hover
        text-decoration: underline

/* 移动端适配 */
@media (max-width 800px)
  .register
    .main
      flex-direction column
      .form-left
        padding-right 0
        .el-form-item
          margin-bottom 0.5rem // 减小间距
          display contents
          align-items center
          .el-form-item__label
            padding-right 0.5rem // 减小 label 和 input 之间的间距
          .el-form-item__content
            flex 1
            .form-input
              width 100%
              height 30px
              font-size 14px
    .divider
      display none
    .upload-right
      padding-left 0
      .avatar-upload
        margin 0 auto 1rem !important
    .footer
      flex-direction: column;
      align-items: center;
      height auto
      gap: 1rem;

</style>
